///* 
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
//
//
//
Components.utils.import("resource:///modules/activity/activityModules.js");
Components.utils.import("resource:///modules/attachmentChecker.js");
Components.utils.import("resource:///modules/cloudFileAccounts.js");
Components.utils.import("resource:///modules/errUtils.js");
Components.utils.import("resource:///modules/folderUtils.jsm");
Components.utils.import("resource:///modules/iteratorUtils.jsm");
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource://gre/modules/InlineSpellChecker.jsm");
Components.utils.import("resource://gre/modules/PluralForm.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource:///modules/editorUtilities.jsm");


Components.utils.import("resource:///modules/FeedUtils.jsm");
Components.utils.import("resource:///modules/gloda/dbview.js");
Components.utils.import("resource:///modules/MailConsts.js");
Components.utils.import("resource://gre/modules/DbTerminal.jsm");
Components.utils.import("resource://gre/modules/k9mailDb.jsm");
//
//
///**
// * interfaces
// */
var nsIMsgCompDeliverMode = Components.interfaces.nsIMsgCompDeliverMode;
var nsIMsgCompSendFormat = Components.interfaces.nsIMsgCompSendFormat;
var nsIMsgCompConvertible = Components.interfaces.nsIMsgCompConvertible;
var nsIMsgCompType = Components.interfaces.nsIMsgCompType;
var nsIMsgCompFormat = Components.interfaces.nsIMsgCompFormat;

var nsIAbPreferMailFormat = Components.interfaces.nsIAbPreferMailFormat;
var nsIPlaintextEditorMail = Components.interfaces.nsIPlaintextEditor;
var nsISupportsString = Components.interfaces.nsISupportsString;
var mozISpellCheckingEngine = Components.interfaces.mozISpellCheckingEngine;
var nsIMsgFolderObj= Components.interfaces.nsIMsgFolder;
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
///*邮件存储实现*/
function nsAttachmentOpener()
{
}

nsAttachmentOpener.prototype =
{
  QueryInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsIURIContentListener) ||
        iid.equals(Components.interfaces.nsIInterfaceRequestor) ||
        iid.equals(Components.interfaces.nsISupports))
        return this;
    throw Components.results.NS_NOINTERFACE;
  },

  onStartURIOpen: function(uri)
  {
    return false;
  },

  doContent: function(contentType, isContentPreferred, request, contentHandler)
  {
    return false;
  },

  isPreferred: function(contentType, desiredContentType)
  {
    return false;
  },

  canHandleContent: function(contentType, isContentPreferred, desiredContentType)
  {
    return false;
  },

  getInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsIDOMWindow))
      return window;
    else
      return this.QueryInterface(iid);
  },

  loadCookie: null,
  parentContentListener: null
}

function findIdentityListId()
{
  var AccAndIdentity=[{AccountId:"accountId", IdentityKey:"id", IdentityName:"emailName"}];  

  var accounts = allAccountsSorted(true);
  //alert(accounts.length);
  for (var acc = 0; acc < accounts.length; acc++) {
    var account = accounts[acc];
 
    var identities = toArray(fixIterator(account.identities,
                                         Components.interfaces.nsIMsgIdentity));
        
    if (identities.length === 0)
      continue;
     //alert(identities.length);
    for (var i = 0; i < identities.length; i++) {
      var identity = identities[i];
             //alert("i="+i);
            var step1Id=identity.identityName.split(">")[0];
      
            var step2Id=step1Id.split("<")[1];
      //alert(account+"==="+identity.key+"====="+step2Id);
      AccAndIdentity.push({AccountId:account,IdentityKey:identity.key, IdentityName:step2Id}) ;
    }
 }
 return AccAndIdentity;
}
function SaveK9mailMessage(accName,messageType)
{   
  //alert(1);
  var nsAttachmentOpener1= new nsAttachmentOpener();
  //var window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);
  var editor1 =document.getElementById("content-frame");
  /*
   * 解析XML数据
   * */
  xmlDoc = document.implementation.createDocument('','',null);
  if(xmlDoc != null)
  {
      xmlDoc.async = false;
      xmlDoc.load("test-002.xml");
  }
 /*get account and identity*/
  var  AccAndIdentity=findIdentityListId();
  var IdentityValue = null;
  var AccountValue =null; 
  var userName=null;

  for(var i=1;i<=AccAndIdentity.length;i++)
  {
      var accidentityObj=AccAndIdentity[i];
      if(accidentityObj.IdentityName==="lijinhai5566@163.com")
      {
          IdentityValue=MailServices.accounts.getIdentity(accidentityObj.IdentityKey);
          AccountValue=accidentityObj.AccountId;
          userName=accidentityObj.IdentityName.split("@")[0];
          //alert(IdentityValue);
          //alert(AccountValue);
          //alert(userName);
          break;        
      }
  }
  if(IdentityValue===null&&AccountValue===null)
  {
    
    IdentityValue = MailServices.accounts.getIdentity("id2");
    AccountValue = "account2";
  }
 // var IdentityValue = getCurrentIdentity();
  //var AccountValue = getCurrentAccountKey(); 
  
  msgCount=xmlDoc.getElementsByTagName("message");
  for (i=0;i<=msgCount.length;i++)
  { 
   var window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);   
   var params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);
   var msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"]
                        .createInstance(Components.interfaces.nsIMsgWindow);
   var progress = Components.classes["@mozilla.org/messenger/progress;1"]
                             .createInstance(Components.interfaces.nsIMsgProgress);
   progress = null;
   gMsgCompose = MailServices.compose.initCompose(params, window1, editor1.docShell);  
   
  //var fccURI = aFolder.URI;
  //alert("fccURI="+fccURI);
  //msgCompFields.fcc2 = (msgCompFields.fcc2 == fccURI) ? "nocopy://" : fccURI;
      
    var msgCompFields = gMsgCompose.compFields;
    var msgSub= xmlDoc.getElementsByTagName("subject")[i].childNodes[0].nodeValue;
    var msgTo = xmlDoc.getElementsByTagName("to_list")[i].childNodes[0].nodeValue;
    var msgContent = xmlDoc.getElementsByTagName("html_content")[i].childNodes[0].nodeValue;
    //var fromvalue=xmlDoc.getElementsByTagName("reply_to_list")[i].childNodes[0].nodeValue;
    
    
    //msgCompFields.fcc2="mailbox://lijinhaiTestTB@pop3.163.com/Sent";//sent
    
    msgCompFields.subject =msgSub;
    msgCompFields.to = msgTo;
    msgCompFields.draftId = i;
    msgCompFields.body = msgContent;
    //msgCompFields.from = fromvalue;
    //alert("jinhai"+msgCompFields.from);
    /*附件存储实现*/
    //  
    //let attachment = Components.classes["@mozilla.org/messengercompose/attachment;1"]
                               //.createInstance(Components.interfaces.nsIMsgAttachment);
    //attachment.url = "file:///home/gyd/%E6%A1%8C%E9%9D%A2/gecko-sdk-i686-pc-linux-gnu-1.8.0.4.tar.bz2";                   
    //msgCompFields. addAttachment(attachment);  
    
    msgWindow.domWindow = window1;
    msgWindow.rootDocShell.allowAuth = true;
    /*
    const long Now = 0;
    const long Later = 1;
    const long Save = 2;
    const long SaveAs = 3;
    const long SaveAsDraft = 4;
    const long SaveAsTemplate = 5;
    const long SendUnsent = 6;
    const long AutoSaveAsDraft = 7;
    const long Background = 8;
   */
   if(messageType==="draft")
   {   
     gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }else if(messageType==="inbox" )
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3.163.com/Inbox";//inbox 
       gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
       
   else if(messageType==="send")
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3.163.com/Sent";
        gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
         
   /*
    * delete many  message
    * 
   var treeTS=document.getElementById("threadTree");
    treeTS.view.selection.rangedSelect(0,8,true);
    goDoCommand('button_shiftDelete');//button_delete
    RestoreFocusAfterHdrButton();
     */
    msgCompFields.draftId=null;
    msgCompFields.subject=null;
    msgCompFields.to=null;
    msgCompFields.body =null;
    window1=null;
    //MailServices.mailSession.RemoveMsgWindow(msgWindow);
    msgWindow = null;
    msgWindow=null;
    //continue;
    //window1.close();
   /// gMsgCompose.CloseWindow(false);event.shiftKey ? 'button_shiftDelete' :
  
    }
    //alert("me");
}


function SaveSelMessageToBox(accName,msgInfo,messageType)
{   
  //alert(1);
  var nsAttachmentOpener1= new nsAttachmentOpener();
  //var window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);
  var editor1 =document.getElementById("content-frame");

  //alert(editor1);
 /*get account and identity*/
 //alert(AccAndIdentity.length);
  var AccAndIdentity=findIdentityListId();
  if(AccAndIdentity.length===1)
  {
      prompts.alert(null, "提示", "请配置邮件所属账户或本地管理终端邮件账户");
      //alert("请配置邮件所属账户或本地管理终端邮件账户");
      return;
  }
  //alert(AccAndIdentity);
  var IdentityValue = null;
  var AccountValue =null; 
  var userName=null;
  var emailSerName=null;
  //alert(AccAndIdentity.length);  
   for(var i=1;i<AccAndIdentity.length;i++)
   {
      var accidentityObj=AccAndIdentity[i];
      if(accidentityObj.IdentityName===accName)
      {
          IdentityValue=MailServices.accounts.getIdentity(accidentityObj.IdentityKey);
          AccountValue=accidentityObj.AccountId;
          userName=accidentityObj.IdentityName.split("@")[0];
          emailSerName=accidentityObj.IdentityName.split("@")[1];
          //alert(IdentityValue);
          //alert(AccountValue);
          //alert(userName);
          break;        
      }
  }
  //alert("emailSerName="+emailSerName);
  if(IdentityValue===null&&AccountValue===null)
  {
    //alert("123");
    var idl=AccAndIdentity.length;
    var idv="id"+idl;
    IdentityValue = MailServices.accounts.getIdentity(idv);
    AccountValue = "account2";
  }
 // var IdentityValue = getCurrentIdentity();
  //var AccountValue = getCurrentAccountKey(); 
  
  for (i=1;i<msgInfo.length;i++)
  { 
   var window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);   
   var params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);
   var msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"]
                        .createInstance(Components.interfaces.nsIMsgWindow);
   var progress = Components.classes["@mozilla.org/messenger/progress;1"]
                             .createInstance(Components.interfaces.nsIMsgProgress);
   progress = null;
   gMsgCompose = MailServices.compose.initCompose(params, window1, editor1.docShell);  
   
  //var fccURI = aFolder.URI;
  //alert("fccURI="+fccURI);
  //msgCompFields.fcc2 = (msgCompFields.fcc2 == fccURI) ? "nocopy://" : fccURI;
      
    var msgCompFields = gMsgCompose.compFields;
    var gmsgSub= msgInfo[i].msgSub;
    var gmsgTo = msgInfo[i].msgTo;
    var gmsgContent = msgInfo[i].msgContent;
    //var fromvalue=xmlDoc.getElementsByTagName("reply_to_list")[i].childNodes[0].nodeValue;
    
    
    //msgCompFields.fcc2="mailbox://lijinhaiTestTB@pop3.163.com/Sent";//sent
    
    msgCompFields.subject =gmsgSub;
    msgCompFields.to = gmsgTo;
    msgCompFields.draftId = i;
    msgCompFields.body = gmsgContent;
    //msgCompFields.from = fromvalue;
    //alert("jinhai"+msgCompFields.from);
    /*附件存储实现*/
    if(msgInfo[i].attUrl!==null)
    {
     var attachment = Components.classes["@mozilla.org/messengercompose/attachment;1"]
                               .createInstance(Components.interfaces.nsIMsgAttachment);
      attachment.url = "file://"+msgInfo[i].attUrl;                   
      msgCompFields. addAttachment(attachment);     
    }
    msgWindow.domWindow = window1;
    msgWindow.rootDocShell.allowAuth = true;
    /*
    const long Now = 0;
    const long Later = 1;
    const long Save = 2;
    const long SaveAs = 3;
    const long SaveAsDraft = 4;
    const long SaveAsTemplate = 5;
    const long SendUnsent = 6;
    const long AutoSaveAsDraft = 7;
    const long Background = 8;
   */
   if(messageType==="draft")
   {   
     gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }else if(messageType==="inbox" )
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3."+emailSerName+"/Inbox";//inbox 
       gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
       
   else if(messageType==="send")
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3."+emailSerName+"/Sent";
        gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
         
   /*
    * delete many  message
    * 
   var treeTS=document.getElementById("threadTree");
    treeTS.view.selection.rangedSelect(0,8,true);
    goDoCommand('button_shiftDelete');//button_delete
    RestoreFocusAfterHdrButton();
     */
    msgCompFields.draftId=null;
    msgCompFields.subject=null;
    msgCompFields.to=null;
    msgCompFields.body =null;
    window1=null;
    //MailServices.mailSession.RemoveMsgWindow(msgWindow);
    msgWindow = null;
    //msgWindow=null;
    //continue;
    //window1.close();
   /// gMsgCompose.CloseWindow(false);event.shiftKey ? 'button_shiftDelete' :
  
    }
    //alert("me");
}
/*获取邮件信息到TB中*/
function getMsgToTB()
{
    //("保存信息至收件箱");
    Components.utils.import("resource://gre/modules/FileUtils.jsm");  
    var treeTS=document.getElementById("deviceThreadTree");
    var idList = [];
    var rangeCount = treeTS.view.selection.getRangeCount();
    for (var i = 0; i < rangeCount; i++){
    var start = {};
    var end = {};
    treeTS.view.selection.getRangeAt(i, start, end);
    for (var c = start.value; c <= end.value; c++){
      var itemObj=treeTS.view.getItemAtIndex(c);
      var itemid=treeTS.view.getItemAtIndex(c).id;
      var dbName=itemObj.getAttribute("statustext");
      //alert(itemid+"=="+dbName);
      idList.push(itemid.split("_")[1]);
     }
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
         SELECT aName  FROM td_account where aXml = :myVal");
                  statement.params.myVal = dbName;
                 
        try {
                 while (statement.executeStep()) {
                        var curAccName=statement.row.aName;
                      }
                   }
                 
        finally {
                  statement.reset();
                } 
    //alert(1);            
    if(dk9Sqlite.onLoad(dbName))
    {
      var msgInfo=[{msgSub:"主题",msgTo:"发件人",msgContent:"邮件体",msgType:"类型",accName:"账户名",attUrl:"附件路径"}];
      var atturlArray=new Array();
       for(var i=0;i<idList.length;i++)
      {  
       var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM attachments WHERE message_id = :myVal");
       statement.params.myVal =idList[i];
       try{
           while(statement.executeStep())
          {
             atturlArray.push(statement.row.name); 
          }
        }
         finally
       {
        statement.reset();
        }
        //alert(2);     
        var attfileurl;
        if(atturlArray.length)
        {    
        var file = FileUtils.getFile("TmpD", [atturlArray[0]]);
        if(file.exists())
        {    
             attfileurl=file.path;
        }else{
             attfileurl=null;
        }   
        }        
       var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM  messages WHERE id = :myVal");
       statement.params.myVal =idList[i];
       try{
         while(statement.executeStep())
         {
            var folderid=statement.row.folder_id;
            if(folderid===1)
            {
                 gmsgType ="inbox";
                        
            }else if(folderid===3)
            {
                 gmsgType ="draft";
                        
            }else if(folderid===6)
            {
                 gmsgType ="send";
            }
            msgInfo.push({msgSub:statement.row.subject,
                          msgTo:statement.row.sender_list,
                          msgContent:statement.row.html_content,
                          accName:curAccName,
                          attUrl:attfileurl});
         }
    }
    finally
    {
        statement.reset();
    }
      }
   //alert("获取数据成功");
   SaveSelMessageToBox(curAccName,msgInfo,"draft");   
   //alert("传送邮件数据至TB"); 
}
}